package com.ht.sps.nh.module;

import com.alibaba.fastjson.JSON;
import com.ht.sps.bui.model.SimpleTreeNode;
import com.ht.sps.dao.UserDao;
import com.ht.sps.nh.entity.TreeMenu;
import com.ht.sps.nh.entity.User;
import com.ht.sps.nh.service.NhUserService;
import com.ht.sps.nh.service.TreeMenuService;
import com.ht.sps.util.CaptchaServiceSingleton;
import com.ht.sps.util.ValidationUtil;
import com.octo.captcha.service.CaptchaServiceException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.*;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.crypto.hash.format.Shiro1CryptFormat;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.*;
import org.nutz.web.ajax.Ajax;
import org.nutz.web.ajax.AjaxReturn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@IocBean
@At("nh/system/users")
public class UserModule {
    private static final Logger log = LoggerFactory.getLogger(UserModule.class);

    @Inject
    private UserDao userDao;

    @Inject
    private NhUserService nhUserService;

    @Inject
    private TreeMenuService treeMenuService;

    /**
     *
     */
    @Inject("java:$conf.get('db_url')")
    private String jdbcUrl;
    //添加@RequiresPermissions拦截器 2014-03-05 start
    //聂玉宽
    @At("/")
    @Ok("th:nh/system/users")
    public void index(HttpServletRequest request) {
        List<String> departmentList = nhUserService.getDepartment();
        log.debug("部门列表：{}", Arrays.toString(departmentList.toArray()));
        List<SimpleTreeNode> trees = getAllTreeMenu();
        request.setAttribute("departmentList", departmentList);
        request.setAttribute("permissionList", trees);
        request.setAttribute("userList", getUserList());
    }

    /**
     * 获取用户列表
     * @return
     */
    @At
    @Ok("fastjson")
    public List getUserList(){
        List<User>  l = nhUserService.findAll();
        List userList = new ArrayList();
        for(int i=0;i<l.size();i++){
            Map userMap = new HashMap();
            User user = l.get(i);
            userMap.put("id",user.getId());
            userMap.put("name",user.getName());
            userMap.put("department",user.getDepartment());
            userMap.put("phone",user.getPhone());
            userMap.put("mobilePhone",user.getMobilePhone());
            userMap.put("username",user.getUsername());
            userMap.put("password",user.getPassword());
            userMap.put("type",user.getType());

            userList.add(userMap);
        }
        return userList;
    }

    /**
     * 获取部门列表
     * @return
     */
    @At
    @Ok("fastjson")
    public List getDepartmentList(){
        List<String> departmentList = nhUserService.getDepartment();
        return departmentList;
    }

    /**
     * 获得所有菜单
     * @return
     *          返回所有菜单BUI树结构数据
     */
    @At
    @Ok("fastjson")
    public  List<SimpleTreeNode> getAllTreeMenu(){
        List<SimpleTreeNode> treeList = new ArrayList();
        //获得所有区域控制器数据
        List<TreeMenu> tmList = treeMenuService.findAll();
        //格式化树控件数据
        if(tmList != null && tmList.size() > 0){
            for(TreeMenu tm : tmList){
                if(tm.getId()!=1){
                    SimpleTreeNode node = new SimpleTreeNode(String.valueOf(tm.getParentId()),String.valueOf(tm.getId()),tm.getMenuName(),treeMenuService.isLeaf(tm.getId()));
                    treeList.add(node);
                }
            }
        }
        return treeList;
    }

    /**
     * 修改用户密码
     * @param userId
     * @param password
     * @return
     */
    @At
    @Ok("fastjson")
    public AjaxReturn changePassword(@Param("userId") int userId, @Param("password") String password) {

        RandomNumberGenerator rng = new SecureRandomNumberGenerator();
        String salt = rng.nextBytes().toBase64();
        String hashedPasswordBase64 = new Sha256Hash(password, salt, 1024).toBase64();
        if (userId > 0) {
            nhUserService.updatePassword(userId, hashedPasswordBase64, salt);
        }

        return Ajax.ok();
    }

    /**
     * 添加或编辑用户信息
     * @param request
     * @param user,roleId
     * @return
     */
    @At
    @Ok("fastjson")
    public  Object insertOrUpdateUser(HttpServletRequest request,@Param("user") User user){

        if (user.getId()!=0){// 更新操作
//            changePassword(user.getId(),user.getPassword());
            nhUserService.updateUser(user);
        }else {// 新增用户
           // log.debug("添加卡信息");
            user.setAccountEnabled(true);
            user.setAccountExpired(false);
            user.setAccountLocked(false);
            user.setCredentialsExpired(false);
            user.setLoginDate(Times.now());
            user.setCreateDate(Times.now());
            user.setLoginFailureCount(0);
            user.setLoginIP("127.0.0.1");
            user.setModifyDate(Times.now());
            nhUserService.insert(user);
            User user1 = nhUserService.findOne(Cnd.where("username","=",user.getUsername()));
            if(user1.getId()>0){
                changePassword(user1.getId(), user1.getPassword());
            }
        }
        return getUserList();
    }

    /**
     * 添加或编辑用户权限信息
     * @param request
     * @param idList,userId
     * @return
     */
    @At
    @Ok("fastjson")
    public  Object insertOrUpdatePermission(HttpServletRequest request,@Param("idList") Long[] idList,@Param("userId") Integer userId){
        List<Long> permissionIdList = new ArrayList<Long>();
        for(int i=0;i<idList.length;i++){
            if(permissionIdList.indexOf(idList[i])==-1){
                permissionIdList.add(idList[i]);
            }
            TreeMenu tm = treeMenuService.fetch(idList[i]);
            if(permissionIdList.indexOf(Long.valueOf(tm.getParentId()))==-1&&tm.getParentId()!=0){
                permissionIdList.add(Long.valueOf(tm.getParentId()));
            }
        }
        nhUserService.insertOrUpdatePermission(userId,permissionIdList);
        return getUserList();
    }

    /**
     * 获取用户权限
     * @param request
     * @param idList,userId
     * @return
     */
    @At
    @Ok("fastjson")
    public  List<Long> getPermission(HttpServletRequest request,@Param("idList") int[] idList,@Param("userId") Long userId){
        return nhUserService.getPermission(userId);
    }

    /**
     * 刪除用戶
     * @param params
     * @return
     */
    @At
    @Ok("fastjson")
    public void deleteUser(@Param("params")String params){
        if(!ValidationUtil.isStringNull(params)){
            List<Long> uIdList =  JSON.parseArray(params, Long.class);
            for(int i=0;i<uIdList.size();i++){
                Long userId = uIdList.get(i);
                nhUserService.delete(userId);
            }
        }
    }

    /**
     * 判断名称是否重复
     * @param username
     * @return
     */
    @At
    @Ok("fastjson")
    public Object checkUsername(@Param("id")Long id,@Param("username")String username){
        return nhUserService.checkUsername(id,username);
    }

    @At
    @GET
    @Ok("th:login")// thymeleaf视图
    public void login() {
    }

	@At
    @POST
	@Fail(">>:/")
	@Ok("json")
	public AjaxReturn login(@Param("username") String username,
			@Param("password") String password,
			@Param("remeberMe") boolean remeberMe,
			HttpServletRequest request) {

		if (Strings.isBlank(username)) {
			return Ajax.fail().setMsg("请输入您的用户名!");
		} else if (Strings.isBlank(password)) {
			return Ajax.fail().setMsg("请输入您的密码!");
		}else {
			try {
                Subject currentUser = SecurityUtils.getSubject();
                UsernamePasswordToken token = new UsernamePasswordToken(username, password);
                token.setRememberMe(remeberMe);
                currentUser.login(token); // 这里的授权,请查看shiro.ini中的nutRealm
                return Ajax.ok();
			} catch (CaptchaServiceException e) {
				return Ajax
						.fail()
						.setMsg("Invalid ID, could not validate unexisting or already validated captcha");
			} catch (LockedAccountException e) {
				return Ajax.fail().setMsg("帐号已被锁定");
			} catch (AuthenticationException e) {
				return Ajax.fail().setMsg("密码错误或用户不存在");
			} catch (Exception e) {
				e.printStackTrace();
				return Ajax.fail().setMsg("登录失败");
			}
		}
	}

	// 没登录就不要登出了
	@RequiresAuthentication
	@At
	@Ok(">>:/")
	public void logout() {
		SecurityUtils.getSubject().logout();
	}

	@At
	public User me() {
		return (User) SecurityUtils.getSubject().getPrincipal();
	}

	// 无需登录,就可以直接访问, 跟没写一样....
	@RequiresGuest
	@At("/ping")
	public Object ping() {
		return Times.now();
	}

	// 需要登录之后才能访问,否则跳转到首页
	@RequiresAuthentication
	@At
	public Object authOnly() {
		return "You are authed!";
	}

}